<template>
  <div class="article-manager">

    <el-card :bordered="false" shadow="never" class="ivu-mt mt16">
      <el-button type="primary" class="bnt" v-db-click @click="addClass">建群</el-button>
      <vxe-table class="mt14" highlight-hover-row :loading="loading" header-row-class-name="false"
        :tree-config="{ children: 'children' }" :data="tableData">
        <vxe-table-column field="team_id" title="群ID" tooltip width="150"></vxe-table-column>
        <vxe-table-column field="name" tree-node title="群名称" min-width="250"></vxe-table-column>
        <vxe-table-column field="icon" title="群头像" min-width="100">
          <template v-slot="{ row }">
            <div class="tabBox_img" v-viewer v-if="row.icon">
              <img v-lazy="row.icon" />
            </div>
          </template>
        </vxe-table-column>


        <vxe-table-column field="date" title="操作" width="120" fixed="right">
          <template v-slot="{ row, index }">
            <el-tag v-if="row.status == 1">已解散 </el-tag>
            <a v-if="row.status == 0" v-db-click @click="showChat(row.team_id)">查看聊天</a>
            <el-divider direction="vertical" v-if="row.status == 0"></el-divider>
            <a v-db-click v-if="row.status == 0" @click="del(row.team_id, '结算群聊')">解散</a>
          </template>
        </vxe-table-column>
      </vxe-table>
    </el-card>

    <!-- 建群 -->
    <el-dialog :title="title" :visible.sync="createModals" :before-close="cancel" :close-on-click-modal="false"
      width="600px">
      <el-form class="form" ref="createFrom" label-width="80px" label-position="left">
        <el-row :gutter="24">

          <el-col>
            <el-form-item label="群组名称:" prop="name">
              <el-input type="text" placeholder="请输入群组名" :maxlength="20" v-model="createFrom.name" />
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="群组头像：">
              <div class="upload-box" v-db-click @click="callPicture('单选')">
                <img v-if="createFrom.avatar" :src="createFrom.avatar" class="image" />
                <i v-if="createFrom.avatar" class="el-icon-error btn" v-db-click @click.stop="removeUser"></i>
                <i v-else class="el-icon-user" />
              </div>
            </el-form-item>
          </el-col>


          <el-col>
            <el-form-item label="群主:" prop="owner_account_id">
              <el-tag v-if="createFrom.owner_account_id && owneruserInfo" closable :disable-transitions="false"
                @close="handleClose()"> {{ owneruserInfo.real_name || owneruserInfo.nickname }}
              </el-tag>

              <el-button v-else class="button-new-tag" size="small" @click="addOwnerAccount">+ 添加群主</el-button>
            </el-form-item>
          </el-col>


          <el-col>
            <el-form-item label="成员:">
              <el-tag v-for="(item, index) in userInfo" :key="index" closable :disable-transitions="false"
                @close="handleCloseDuo(index)"> {{ item.real_name || item.nickname }}
              </el-tag>

              <el-button class="button-new-tag" size="small" @click="addAccount">+ 添加成员</el-button>
            </el-form-item>
          </el-col>



          <el-col>
            <el-form-item label="群组公告:" prop="announcement">
              <el-input type="textarea" placeholder="请输入群组公告" v-model="createFrom.announcement" />
            </el-form-item>
          </el-col>


          <el-col>
            <el-form-item label="群组简介:" prop="intro">
              <el-input type="textarea" placeholder="请输入群组简介" v-model="createFrom.intro" />
            </el-form-item>
          </el-col>


          <el-col>
            <el-form-item label="进群附言:" prop="invite_msg">
              <el-input type="textarea" placeholder="请输入进群附言" v-model="createFrom.invite_msg" />
            </el-form-item>
          </el-col>

        </el-row>


        <div class="acea-row row-left">
          <el-button type="primary" @click="createGroup()">创建</el-button>
          <el-button @click="createModals = false">取消</el-button>
        </div>


      </el-form>
    </el-dialog>

    <!-- 上传头像 -->
    <el-dialog :visible.sync="pictureModal" width="950px" title="上传图" :close-on-click-modal="false">
      <uploadPictures :isChoice="isChoice" @getPic="getPic" :gridBtn="gridBtn" :gridPic="gridPic" v-if="pictureModal">
      </uploadPictures>
    </el-dialog>

    <!-- 选择群主 -->
    <el-dialog :visible.sync="userModal_one" width="950px" title="选择群主" :close-on-click-modal="false">

      <el-form :inline="true" :model="userForm" label-width="40px" label-position="left">
        <el-row :gutter="24">
          <el-col>
            <el-form-item label="搜索">
              <el-input v-model="userForm.key_word" placeholder="请输入用户名/UID"></el-input>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getUserList(1)">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="userLists_one" ref="table_one" class="mt20" v-loading="loading_one" highlight-current-row
        no-formValidate-text="暂无数据" no-filtered-formValidate-text="暂无筛选结果">

        <el-table-column width="50">
          <template slot-scope="scope">
            <el-radio v-model="radioData.uid" :label="scope.row.uid" @change.native="currentidRadio(scope.row)">{{
              }}</el-radio>
          </template>
        </el-table-column>

        <el-table-column label="用户UIDone">
          <template slot-scope="scope">
            <span>{{ scope.row.uid }}</span>
          </template>
        </el-table-column>

        <el-table-column label="头像">
          <template slot-scope="scope">
            <div class="tabBox_img" v-viewer>
              <img v-lazy="scope.row.avatar" />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="姓名">
          <template slot-scope="scope">
            <div class="acea-row">
              <i class="el-icon-male mr10" v-show="scope.row.sex === '男'" style="color:#2db7f5;font-size: 15px;"></i>
              <i class="el-icon-female mr10" v-show="scope.row.sex === '女'" style="color:#ed4014;font-size: 15px;"></i>
              <div v-text="scope.row.real_name || scope.row.nickname" class=""></div>
            </div>
          </template>
        </el-table-column>

      </el-table>

      <div class="acea-row row-right page">
        <pagination v-if="total_one" :total="total_one" :page.sync="userForm.page" :limit.sync="userForm.limit"
          @pagination="getUserList" />
      </div>
      <div class="acea-row row-left">
        <el-button type="primary" @click="selectUser()">确定</el-button>
        <el-button @click="userModal_one = false">取消</el-button>
      </div>
    </el-dialog>


    <!-- 选择成员 -->
    <el-dialog :visible.sync="userModal_duo" width="950px" title="选择成员" :close-on-click-modal="false">

      <el-form :inline="true" :model="userForm" label-width="40px" label-position="left">
        <el-row :gutter="24">
          <el-col>
            <el-form-item label="搜索">
              <el-input v-model="userForm.key_word" placeholder="请输入用户名/UID"></el-input>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getUserList(1)">搜索</el-button>

          </el-col>
        </el-row>
      </el-form>
      <!-- 成员多选 -->

      <el-table :data="userLists_duo" ref="table" class="mt20" v-loading="loading_duo" highlight-current-row
        no-formValidate-text="暂无数据" no-filtered-formValidate-text="暂无筛选结果" @select="handleSelectRow"
        @select-all="handleSelectAll">


        <el-table-column type="selection" width="50"></el-table-column>


        <el-table-column label="用户UID">
          <template slot-scope="scope">
            <span>{{ scope.row.uid }}</span>
          </template>
        </el-table-column>
        <el-table-column label="头像">
          <template slot-scope="scope">
            <div class="tabBox_img" v-viewer>
              <img v-lazy="scope.row.avatar" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名">
          <template slot-scope="scope">
            <div class="acea-row">
              <i class="el-icon-male mr10" v-show="scope.row.sex === '男'" style="color:#2db7f5;font-size: 15px;"></i>
              <i class="el-icon-female mr10" v-show="scope.row.sex === '女'" style="color:#ed4014;font-size: 15px;"></i>
              <div v-text="scope.row.real_name || scope.row.nickname" class=""></div>
            </div>
          </template>
        </el-table-column>

      </el-table>
      <div class="acea-row row-right page">
        <pagination v-if="total_duo" :total="total_duo" :page.sync="userForm.page" :limit.sync="userForm.limit"
          @pagination="getUserList()" />
      </div>
      <div class="acea-row row-left">
        <el-button type="primary" @click="selectUser()">确定</el-button>
        <el-button @click="userModal_duo = false">取消</el-button>
      </div>
    </el-dialog>


    <!-- 查看聊天 -->
    <el-dialog :visible.sync="chatShow" title="聊天记录" width="540px" :close-on-click-modal="false">

      <template>
        <!-- <ul class="infinite-list" @v-infinite-scroll="loadChat" style="overflow:auto;height: 400px;"> -->
        <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto;height: 400px;">

          <li v-for="(item, index)  in chatList">

            <div class="tabBox">

              <div class="tabBox_img" v-viewer>
                <img v-lazy="item.avatar" />
                <div>{{ item.nickname }} </div>
              </div>
              <div class="tabBox_content">
                <span>{{ item.text }}</span>
              </div>

              <el-divider content-position="center">

                <span style="color: #ccc;">{{ item.time }}</span>


              </el-divider>

            </div>
          </li>
        </ul>
      </template>

    </el-dialog>

  </div>
</template>

<script>
import { mapState } from 'vuex';

import { createImUser, getTeamListApi, userList, createImGroup, getChatDataApi } from '@/api/user';

import uploadPictures from '@/components/uploadPictures';
export default {
  name: 'product_productClassify',
  components: {
    uploadPictures,

  },
  data() {
    return {
      team_id: 0,
      title: "创建群聊",
      chatShow: false,
      createModals: false,
      createFrom: {
        name: '',
        avatar: '',
        announcement: '',
        invite_msg: '',
        intro: '',
        owner_account_id: '',
        invite_account_ids: [],
      },

      owneruserInfo: {}, // 群主信息
      userInfo: [], // 成员信息
      userLists_one: [], // 选择列表
      userLists_duo: [], // 选择列表
      userForm: {
        key_word: '',
        page: 1,
        limit: 10,
      },

      chatForm: {
        date: '',
        page: '',
        limit: 3,
      },

      pictureModal: false,
      isChoice: '单选',
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8,
      },

      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12,
      },

      userModal_duo: false,
      userModal_one: false,
      userModalType: 'one',
      selectUserTitle: '选择群主',
      radioData: {
        uid: '',
        info: {}
      },

      FromData: null,

      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },

      loading: false,
      loading_duo: false,
      loading_one: false,
      artFrom: {
        pid: 0,
        is_show: '',
        page: 1,
        cate_name: '',
        limit: 15,
      },
      total: 0,
      total_duo: 0,
      total_one: 0,
      total_chat: 0,
      tableData: [],
      chatList: [],
    };
  },

  mounted() {

    this.getList();
    // createImUser()
  },
  methods: {

    // 加载更多聊天
    load() {
      console.log('scroll')
      if (this.chatForm.page) {
        this.getChatList();
      }
    },

    showChat(team_id) {
      this.team_id = team_id;
      this.chatShow = true;
      this.chatForm.page = '';
      this.chatList = [];
      let date = new Date();
      this.chatForm.date = date.toLocaleString(); // 格式化时间戳为可读的日期和时间
      this.getChatList();
    },

    getChatList(val) {
      if (val) {
        this.chatForm.page = val;
      }

      getChatDataApi(this.team_id, this.chatForm).then(
        res => {
          // console.log(res)
          this.chatList = this.chatList.concat(res.data.items);
          this.chatForm.page = res.data.next_token;
          console.log('chatList')
          console.log(this.chatList)
        }
      )
    },


    // 建群
    createGroup() {
      // 加个浮层。
      const loading = this.$loading({
        lock: true,
        text: '正在生成群聊...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.createFrom.invite_account_ids = this.userInfo;

      console.log(this.createFrom)

      createImGroup(this.createFrom).then(res => {
        loading.close();
        this.$message({
          message: '创建成功',
          type: 'success'
        });
        this.createModals = false;
        this.getList();
      }).catch((res) => {
        loading.close();
        this.$message({
          message: res.msg,
          type: 'error'
        })
      });

    },

    //全选和取消全选时触发
    handleSelectAll(selection) {
      console.log(selection);
      // 判断selection中的元素是否在userInfo中,不在就追加进去
      let existingUids = new Set(this.userInfo.map(user => user.uid));
      selection.forEach(item => {
        if (!existingUids.has(item.uid)) {
          // 如果不在集合中，则将其添加到 userInfo 中
          this.userInfo.push(item);
        }
      });

    },
    //  选中某一行
    handleSelectRow(selection, row) {

      console.log(selection);
      // 判断selection中的元素是否在userInfo中,不在就追加进去
      let existingUids = new Set(this.userInfo.map(user => user.uid));
      selection.forEach(item => {
        if (!existingUids.has(item.uid)) {
          // 如果不在集合中，则将其添加到 userInfo 中
          this.userInfo.push(item);
        }
      });

    },
    // 选择用户
    getUserList(page) {
      if (page) {
        this.userForm.page = page;
      }
      userList(this.userForm)
        .then(async (res) => {
          let data = res.data;
          if (this.userModalType == 'duo') {
            this.userLists_duo = data.list;
            this.total_duo = data.count;
            this.loadind_duo = false;
          } else {
            this.userLists_one = data.list;
            this.total_one = data.count;
            this.loadind_one = false;
          }
        })
        .catch((res) => {
          if (this.userModalType == 'one') {
            this.loadind_one = false;
          } else {
            this.loadind_one = false;
          }
          this.$message.error(res.msg);
        });
    },
    // 群主
    handleClose(tag) {

      this.createFrom.owner_account_id = '';
      this.owneruserInfo = {};
    },

    handleCloseDuo(index) {
      console.log('关闭');
      console.log(index);
      this.userInfo.splice(index, 1);
      // userInfo
    },

    currentidRadio(row) {
      this.radioData.uid = row.uid;
      this.radioData.info = row
      console.log(row, 'row')
    },

    addOwnerAccount() {
      this.userModalType = 'one';
      this.userModal_one = true;
      this.getUserList(1);

    },

    addAccount() {
      this.userModalType = 'duo';
      this.userModal_duo = true;
      this.getUserList(1);
    },

    // 确认选择
    selectUser() {
      // 选择群主
      if (this.userModalType == 'one') {
        this.createFrom.owner_account_id = this.radioData.uid;
        this.owneruserInfo = this.radioData.info;
        this.userModal_one = false;
        // 选择成员
      } else if (this.userModalType == 'duo') {
        this.userModal_duo = false;
      }

    },

    // 头像
    removeUser() {
      this.createFrom.avatar = '';

    },
    getPic(img) {
      console.log(img, '图片');
      this.createFrom.avatar = img.att_dir;
      this.pictureModal = false;
    },

    callPicture(type) {
      this.isChoice = type;
      this.pictureModal = true;
    },

    // 列表
    getList() {
      if (this.userModalType = 'duo') {
        this.loading_duo = true;
      } else {
        this.loading_one = true;
      }

      this.artFrom.is_show = this.artFrom.is_show || '';
      this.artFrom.pid = this.artFrom.pid || '';
      getTeamListApi(this.artFrom)
        .then(async (res) => {
          let data = res.data;
          this.tableData = data.list;
          this.total = data.count;

          if (this.userModalType = 'duo') {
            this.loading_duo = false;
          } else {
            this.loading_one = false;
          }
        })
        .catch((res) => {
          if (this.userModalType = 'duo') {
            this.loading_duo = false;
          } else {
            this.loading_one = false;
          }
          this.$message.error(res.msg);
        });
    },
    pageChange(index) {
      this.artFrom.page = index;
      this.getList();
    },
    // 添加
    addClass() {
      this.createModals = true;
      //this.$modalForm(courseCateCreateApi()).then(() => this.getList());
    },
    // 编辑
    edit(row) {
      this.$modalForm(courseCateEditApi(row.id)).then(() => this.getList());
    },
    cancel() {
      this.createModals = false;
    },
    // 修改状态
    onchangeIsShow(row) {
      let data = {
        id: row.id,
        is_show: row.is_show,
      };
      setShowApi(data)
        .then(async (res) => {
          this.$message.success(res.msg);
        })
        .catch((res) => {
          this.$message.error(res.msg);
        });
    },
    // 下拉树
    handleCheckChange(data) {
      let value = '';
      let title = '';
      this.list = [];
      this.artFrom.pid = 0;
      data.forEach((item, index) => {
        value += `${item.id},`;
        title += `${item.title},`;
      });
      value = value.substring(0, value.length - 1);
      title = title.substring(0, title.length - 1);
      this.list.push({
        value,
        title,
      });
      this.artFrom.pid = value;
      this.getList();
    },
    // 删除
    del(team_id, tit) {
      this.$confirm('确定要将该群解散吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTeam(team_id)
          .then((res) => {
            this.$message({
              type: 'success',
              message: '已解散!'
            });
            this.getList()
          })
          .catch((res) => {
            this.$message.error(res.msg);
          });


      }).catch(() => {

      });




      let delfromData = {
        title: tit,
        url: `im/del_team/${team_id}`,
        method: 'get',
      };
      this.$modalSure(delfromData)
        .then((res) => {
          this.$message.success(res.msg);
          this.getList();
        })
        .catch((res) => {
          this.$message.error(res.msg);
        });
    },
    // 表格搜索
    userSearchs() {
      this.artFrom.page = 1;
      this.getList();
    },
  },
};
</script>
<style scoped>
.treeSel ::v-deep .ivu-select-dropdown-list {
  padding: 0 10px !important;
  box-sizing: border-box;
}


.upload-box {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 58px;
  height: 58px;
  border: 1px dashed #c0ccda;
  border-radius: 4px;

  vertical-align: middle;
  text-align: center;
  line-height: 58px;
  cursor: pointer;

  +.upload-box {
    margin-left: 10px;
  }

  .ivu-icon {
    vertical-align: middle;
    font-size: 20px;
  }

  .image {
    width: 100%;
    height: 100%;
    border-radius: 3px;
  }

  .btn {
    position: absolute;
    top: 0;
    right: 0;
    font-size: 14px;
    transform: translate(50%, -50%);
  }

  .tabBox {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  

}

.tabBox_img {
  display: inline;
     
    align-items: center;

    img {
      cursor: pointer;
      float: left;
      width: 36px;
      height: 36px;
      border: 1px solid #ccc;
      border-radius: 100%;
     
    }

    div {
      line-height: 36px;
      margin-left: 46px;;
      width : 200px;
      height: 36px;
      font-size: 14px;
      color: #333;
    }
  }

  .tabBox_content {
    margin-top: 18px;
  }

  .tabBox_content span {
    font-size: 16px;
    color: #555;
  }
</style>
